package com.lancoo.znbkxx.teacher.ui.fragment

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.android.tu.loadingdialog.LoadingDailog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.EvenItemDecoration
import com.lancoo.znbkxx.teacher.adapter.GridMediaAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtMyCommentBinding
import com.lancoo.znbkxx.teacher.ui.activity.VideoPlayerActivity
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.GlideEngine
import com.lancoo.znbkxx.teacher.utils.ToastUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia

import org.json.JSONArray
import org.json.JSONObject

/**
 * Created by wealive on 2021/3/2.
 *
 *
 */
class MyCommentFragment : BaseVMFragment<HardSolutionViewModel, FmtMyCommentBinding>(),
        View.OnClickListener, BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemChildClickListener {
    private var isCamera: Boolean = true
    private lateinit var cameraMenu: PopupWindow
    private lateinit var adapter: GridMediaAdapter
    private val navigationHeight by lazy {
        resources.getDimensionPixelSize(
                resources.getIdentifier("navigation_bar_height", "dimen", "android"))
    }
    var selectList = mutableListOf<LocalMedia>()
    var tempList = mutableListOf<LocalMedia>()
    private val audioList = arrayListOf<LocalMedia>()
    private var tempAudioList = arrayListOf<LocalMedia>()
    private val GET_PERMISSION_REQUEST = 100 //权限申请自定义码
    private lateinit var content: String
    private val audioPath by lazy { viewModel.answerSkillComment.value?.AudioPath }
    private val imagePath by lazy { viewModel.answerSkillComment.value?.PicturePath }
    private val videoPath by lazy { viewModel.answerSkillComment.value?.VideoPath }
    lateinit var video: LocalMedia
    override fun setLayoutID(): Int {
        return R.layout.fmt_my_comment
    }

    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    override fun providerContext(): Any? {
        return activity
    }

    override fun initView() {
        initEditText()
        initPopWindow()
        initRecyclerView()
//        Handler().post {
//            (activity as AnswerSkillCommentActivity).loadingDialog.dismiss()
//        }
    }

    private fun initEditText() {
        content = viewModel.answerSkillComment.value?.SolutionContent!!
        binding.edtContent.setText(content)
    }

    private fun initPopWindow() {
        val mPopView = layoutInflater.inflate(R.layout.view_note_edit, null)
        val tvCancel = mPopView.findViewById<TextView>(R.id.tv_cancel)
        val tvPhotograph = mPopView.findViewById<TextView>(R.id.tv_photograph)
        val tvFromAlbum = mPopView.findViewById<TextView>(R.id.tv_fromAlbum)
        tvCancel.setOnClickListener(this)
        tvPhotograph.setOnClickListener(this)
        tvFromAlbum.setOnClickListener(this)
        cameraMenu = PopupWindow(mPopView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT)
        cameraMenu.isOutsideTouchable = true
        //获取焦点
        cameraMenu.isFocusable = true
        cameraMenu.animationStyle = R.style.PopupWindow
        cameraMenu.setOnDismissListener {
            val lp = requireActivity().window.attributes
            lp.alpha = 1f
            requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            requireActivity().window.attributes = lp
        }
    }

    private fun initRecyclerView() {
        val manager = GridLayoutManager(activity, 3)
        binding.rv.layoutManager = manager
        binding.rv.addItemDecoration(EvenItemDecoration(DensityUtils.dp2px(activity, 10f), 3))
        adapter = GridMediaAdapter(R.layout.item_preview, selectList, viewModel.videoMap.value)
        adapter.onItemClickListener = this
        adapter.onItemChildClickListener = this
        binding.rv.adapter = adapter
        if (!audioPath!!.isBlank()) {
            val recordList = JSONArray(audioPath)
            for (i in 0 until recordList.length()) {
                val item = recordList.getJSONObject(i)
                val media = LocalMedia()
                val path = item.getString("src")
                //                    media.key = path
                media.path = Ext.OBSINFO?.ServerWithBucket + path
                media.mimeType = "audio/" + path.substring(path.lastIndexOf(".") + 1)
                //                    media.mimeType = 3
                audioList.add(media)
            }
        }
        if (!imagePath!!.isBlank() && !imagePath!!.contains("{}")) {
            val imgList = JSONArray(imagePath)
            for (i in 0 until imgList.length()) {
                val item = imgList.getJSONObject(i)
                val media = LocalMedia()
                val path = item.getString("src")
                //                    media.key = path
                media.path = Ext.OBSINFO?.ServerWithBucket + path
                media.mimeType = "image/" + path.substring(path.lastIndexOf(".") + 1)
                //                    media.mimeType = 1
                selectList.add(media)
            }
        }
        if (!videoPath!!.isBlank()) {
            //                hasVideo = true
            val videoList: JSONArray
            val item: JSONObject
            val path: String
            if (videoPath!!.contains("src")) {
                videoList = JSONArray(videoPath)
                item = videoList.getJSONObject(0)
                path = item.getString("src")
            } else {
                path = videoPath!!
            }
            video = LocalMedia()
            video.path = Ext.OBSINFO?.ServerWithBucket + path
            video.mimeType = "video/" + path.substring(path.lastIndexOf(".") + 1)
            selectList.add(video)
            viewModel.saveVideoInfo(video.path)
        }
        tempList.addAll(selectList)
        tempAudioList.addAll(audioList)
    }

    private fun showPopWindow() {
        cameraMenu.showAtLocation(binding.cv, Gravity.BOTTOM, 0, navigationHeight)
        val lp = requireActivity().window.attributes
        lp.alpha = 0.4f
        requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        requireActivity().window.attributes = lp
    }

    private fun checkCameraPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ContextCompat.checkSelfPermission(requireContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
        } else {
            true
        }
    }

    override fun startObserve() {
        viewModel.mediaList.observe(this, Observer {
            adapter.setNewData(it)
        })

        viewModel.videoMap.observe(this, Observer {
            adapter.updateMap(it)
        })
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_cancel -> cameraMenu.dismiss()
            R.id.tv_photograph -> {
                isCamera = true
                cameraMenu.dismiss()
                if (checkCameraPermission()) {
                    PictureSelector.create(this).openCamera(PictureMimeType.ofImage())
                            .isCompress(true).selectionData(selectList)
                            .forResult(PictureConfig.CHOOSE_REQUEST)
                } else {
                    //不具有获取权限，需要进行权限申请
                    requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA),
                            GET_PERMISSION_REQUEST)
                }
            }
            R.id.tv_fromAlbum -> {
                isCamera = false
                cameraMenu.dismiss()
                if (checkCameraPermission()) {
                    PictureSelector.create(this).openGallery(PictureMimeType.ofImage())
                            .imageEngine(GlideEngine.createGlideEngine()).maxSelectNum(5)
                            .isCamera(false).isCompress(true).videoMinSecond(4)
                            .selectionData(selectList.apply {
                                if (this@MyCommentFragment::video.isInitialized) {
                                    remove(video)
                                }
                            }).forResult(PictureConfig.CHOOSE_REQUEST)
                } else {
                    //不具有获取权限，需要进行权限申请
                    requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA),
                            GET_PERMISSION_REQUEST)
                }
            }
        }
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        if (position == selectList.size) {
            showPopWindow()
        } else {
            val media = selectList[position]
            val pictureType = media.mimeType
            when {
                pictureType.contains("image") ->
                    // 预览图片 可自定长按保存路径
                    PictureSelector.create(this).themeStyle(R.style.picture_default_style)
                            .imageEngine(GlideEngine.createGlideEngine())
                            .openExternalPreview(position, selectList)
                pictureType.contains("video") -> {
                    // 预览视频
                    //                        PictureSelector.create(this).externalPictureVideo(media.path)
                    val videoPath = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                        media.androidQToPath else media.path
                    val intent = Intent(activity, VideoPlayerActivity::class.java).putExtra(
                            "VideoPath", videoPath ?: media.path)
                    startActivity(intent)
                }
                pictureType.contains("audio") ->
                    // 预览音频
                    PictureSelector.create(this).externalPictureAudio(media.path)
            }
        }
    }


    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        when (view?.id) {
            R.id.iv_delete -> {
                selectList.removeAt(position)
                adapter?.notifyItemRemoved(position)
                adapter?.notifyItemRangeChanged(position, selectList.size)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == AppCompatActivity.RESULT_CANCELED) {
            return
        }
        when (requestCode) {
            PictureConfig.CHOOSE_REQUEST -> {
                // 图片、视频、音频选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data)
                if (this::video.isInitialized) {
                    selectList.add(video)
                }
                viewModel.mediaList.value = selectList
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
                                            grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == GET_PERMISSION_REQUEST) {
            var size = 0
            if (grantResults.isNotEmpty()) {
                val writeResult = grantResults[0]
                //读写内存权限
                val writeGranted = writeResult == PackageManager.PERMISSION_GRANTED //读写内存权限
                if (!writeGranted) {
                    size++
                }
                //录音权限
                val recordPermissionResult = grantResults[1]
                val recordPermissionGranted = recordPermissionResult == PackageManager.PERMISSION_GRANTED
                if (!recordPermissionGranted) {
                    size++
                }
                //相机权限
                val cameraPermissionResult = grantResults[2]
                val cameraPermissionGranted = cameraPermissionResult == PackageManager.PERMISSION_GRANTED
                if (!cameraPermissionGranted) {
                    size++
                }
                if (size == 0) {
                    if (isCamera) {
                        PictureSelector.create(this).openCamera(PictureMimeType.ofImage())
                                .isCompress(true).selectionData(selectList)
                                .forResult(PictureConfig.CHOOSE_REQUEST)
                    } else {
                        PictureSelector.create(this).openGallery(PictureMimeType.ofImage())
                                .imageEngine(GlideEngine.createGlideEngine()).maxSelectNum(5)
                                .isCamera(false).isCompress(true).videoMinSecond(4)
                                .selectionData(selectList.apply {
                                    if (this@MyCommentFragment::video.isInitialized) {
                                        remove(video)
                                    }
                                }).forResult(PictureConfig.CHOOSE_REQUEST)
                    }
                } else {
//                    Toast.makeText(activity, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show()
                    MyToast.showToast("请到设置-权限管理中开启")
                }
            }
        }
    }
}